package com.zy.qudadid.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yancy.imageselector.ImageConfig;
import com.yancy.imageselector.ImageSelector;
import com.yancy.imageselector.ImageSelectorActivity;
import com.zy.lcpassenger.R;
import com.zy.qudadid.ui.view.OwnInfoView;
import com.zy.qudadid.model.User;
import com.zy.qudadid.presenter.OwnInfoPresenter;
import com.zy.qudadid.ui.activity.base.ToolBarActivity;
import com.zy.qudadid.ui.widget.CustomImageView;
import com.zy.qudadid.ui.widget.InputCareerDialog;
import com.zy.qudadid.ui.widget.InputNameDialog;
import com.zy.qudadid.ui.widget.RoundCornerImageView;
import com.zy.qudadid.ui.widget.SignatureDialog;
import com.zy.qudadid.utils.AESCrypt;
import com.zy.qudadid.utils.GlideLoader;
import com.zy.qudadid.utils.StringUtil;
import com.zy.qudadid.utils.ToolsUtil;
import com.zy.qudadid.utils.UserUtil;

import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.picker.OptionPicker;
import cn.qqtheme.framework.picker.SexPicker;

/**
 * Created by ASUS on 2017/3/5.
 */

public class OwnInfoActivity extends ToolBarActivity<OwnInfoPresenter> implements OwnInfoView {
    @Bind(R.id.img_own_image)
    CustomImageView img_own_image;
    @Bind(R.id.rl_name)
    RelativeLayout rlName;
    @Bind(R.id.rl_sex)
    RelativeLayout rlSex;
    @Bind(R.id.rl_age)
    RelativeLayout rlAge;
    @Bind(R.id.rl_phone)
    RelativeLayout rlPhone;
    @Bind(R.id.rl_signature)
    RelativeLayout rlSignature;
    @Bind(R.id.rl_career)
    RelativeLayout rl_career;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_sex)
    TextView tvSex;
    @Bind(R.id.tv_age)
    TextView tvAge;
    @Bind(R.id.tv_signature)
    TextView tvSignature;
    @Bind(R.id.tv_career)
    TextView tv_career;

    private String str_tvSignature,str_tvName,str_tv_career,str_sex,str_age;

    @Override
    protected void initThings(Bundle savedInstanceState) {
        super.initThings(savedInstanceState);

        User user = new UserUtil(this).getUser();
        tvName.setText(user.username);
        tvSex.setText(user.sex);
        tvAge.setText(user.age);
        tv_career.setText(user.zhiye);
        tvSignature.setText(user.nickname);
        Glide.with(this)
                .load(user.avatar)
                .placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
                .centerCrop()
                .into(img_own_image);


        Map map = new HashMap();
        map.put("user_id", new UserUtil(OwnInfoActivity.this).getUserId());
        map.put("type", 1);
        String json = StringUtil.toJson(map);
        try {
            String data1 = AESCrypt.getInstance().encrypt(json);
            String d = StringUtil.replaceBlank(data1);
            presenter.InquireInfo(d);
        } catch (Exception ex) {
        }
    }

    @Override
    protected CharSequence provideTitle() {
        return "个人信息";
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_own_info;
    }

    @Override
    public void initListeners() {

    }

    @Override
    public OwnInfoPresenter createPresenter() {
        return new OwnInfoPresenter();
    }

    @OnClick({R.id.img_own_image, R.id.rl_name, R.id.rl_signature,R.id.rl_sex,R.id.rl_age,R.id.rl_career})
    protected void img_onClick(View view) {
        switch (view.getId()) {
            case R.id.img_own_image://设置头像
                ImageConfig imageConfig
                        = new ImageConfig.Builder(new GlideLoader())
                        .steepToolBarColor(getResources().getColor(R.color.theme_color))
                        .titleBgColor(getResources().getColor(R.color.theme_color))
                        .titleSubmitTextColor(getResources().getColor(R.color.white))
                        .titleTextColor(getResources().getColor(R.color.white))
                        // 开启单选   （默认为多选）
                        .singleSelect()
                        // 开启拍照功能 （默认关闭）
                        .showCamera()
                        // 拍照后存放的图片路径（默认 /temp/picture） （会自动创建）
                        .filePath("/ImageSelector/Pictures")
                        .build();

                ImageSelector.open(OwnInfoActivity.this, imageConfig);   // 开启图片选择器
                break;
            case R.id.rl_name://昵称
                final InputNameDialog inputNameDialog = new InputNameDialog(getContext());
                inputNameDialog.tv_oncar_yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//确认昵称
                        str_tvName = inputNameDialog.tv_content.getText().toString();
                        tvName.setText(str_tvName);
                        inputNameDialog.dismiss();

                        Map map = new HashMap();
                        map.put("id", new UserUtil(OwnInfoActivity.this).getUserId());
                        map.put("uname", str_tvName);
                        String json = StringUtil.toJson(map);
                        try {
                            String data1 = AESCrypt.getInstance().encrypt(json);
                            String d = StringUtil.replaceBlank(data1);
                            presenter.ChangeInfo(d);
                        } catch (Exception ex) {
                        }
                    }
                });
                inputNameDialog.tv_oncar_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//取消
                        inputNameDialog.dismiss();
                    }
                });
                break;
            case R.id.rl_signature://我的签名
                final SignatureDialog signatureDialog = new SignatureDialog(getContext());
                signatureDialog.tv_oncar_yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//确认签名
                        str_tvSignature = signatureDialog.tv_content.getText().toString();
                        tvSignature.setText(str_tvSignature);
                        signatureDialog.dismiss();

                        Map map = new HashMap();
                        map.put("id", new UserUtil(OwnInfoActivity.this).getUserId());
                        map.put("nkame", str_tvSignature);
                        String json = StringUtil.toJson(map);
                        try {
                            String data1 = AESCrypt.getInstance().encrypt(json);
                            String d = StringUtil.replaceBlank(data1);
                            presenter.ChangeInfo(d);
                        } catch (Exception ex) {
                        }
                    }
                });
                signatureDialog.tv_oncar_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//取消
                        signatureDialog.dismiss();
                    }
                });
                break;
            case R.id.rl_sex://性别
                onChooseSex();
                break;
            case R.id.rl_age://年龄
                onChooseYearAndMonth();
                break;
            case R.id.rl_career://公司-职业
                final InputCareerDialog inputCareerDialog = new InputCareerDialog(getContext());
                inputCareerDialog.tv_oncar_yes.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//确认职业
                        inputCareerDialog.dismiss();
                        str_tv_career = inputCareerDialog.tv_content.getText().toString()+"  "+inputCareerDialog.tv_content2.getText().toString();
                        tv_career.setText(str_tv_career);

                        Map map = new HashMap();
                        map.put("id", new UserUtil(OwnInfoActivity.this).getUserId());
                        map.put("zhiye", str_tv_career);
                        String json = StringUtil.toJson(map);
                        try {
                            String data1 = AESCrypt.getInstance().encrypt(json);
                            String d = StringUtil.replaceBlank(data1);
                            presenter.ChangeInfo(d);
                        } catch (Exception ex) {
                        }
                    }
                });
                inputCareerDialog.tv_oncar_no.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {//取消
                        inputCareerDialog.dismiss();
                    }
                });
                break;
            default:

                break;
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ImageSelector.IMAGE_REQUEST_CODE && resultCode == RESULT_OK && data != null) {

            // Get Image Path List
            List<String> pathList = data.getStringArrayListExtra(ImageSelectorActivity.EXTRA_RESULT);

//            for (String path : pathList) {
//                Log.i("ImagePathList", path);
//            }
            String path = pathList.get(0);
            Glide.with(this)
                    .load(path)
                    .centerCrop()
                    .crossFade()
                    .placeholder(R.drawable.userimg)
                    .into(img_own_image);

            User user = new UserUtil(this).getUser();
            presenter.changeAvatar(user.mobile, user.id, path);
        }
    }

    @Override
    public void successChangeAvatar() {
        toast("头像上传成功");
    }

    @Override
    public void errorChangeAvatar(String msg) {

    }

    @Override
    public void successChangeOwnInfo() {
        ToolsUtil.print("----","信息修改成功");

        User user = new UserUtil(this).getUser();
        user.name = str_tvName;
        user.sex = str_sex;
        user.age = str_age;
        user.zhiye = str_tv_career;
        user.nickname = str_tvSignature;
        new UserUtil(this).removeUserInfo();
        new UserUtil(this).putUser(user);
    }

    @Override
    public void errorChangeOwnInfo(String msg) {

    }

    @Override
    public void successInquireInfo(User user1) {
        ToolsUtil.print("----","查询个人信息成功");

        User user = new UserUtil(this).getUser();
//        user.name = str_tvName;
//        user.sex = str_sex;
//        user.age = str_age;
//        user.zhiye = str_tv_career;
//        user.nickname = str_tvSignature;
//        user.avatar = str_tvSignature;

        user.username = user1.username;
        user.sex = user1.sex;
        user.age = user1.age;
        user.zhiye = user1.zhiye;
        user.nickname = user1.nickname;
        user.avatar = user1.avatar;
        new UserUtil(this).removeUserInfo();
        new UserUtil(this).putUser(user);

        tvName.setText(user.username);
        tvSex.setText(user.sex);
        tvAge.setText(user.age);
        tv_career.setText(user.zhiye);
        tvSignature.setText(user.nickname);
        Glide.with(this)
                .load(user.avatar)
                .placeholder(com.yancy.imageselector.R.mipmap.imageselector_photo)
                .centerCrop()
                .into(img_own_image);
    }

    @Override
    public void errorInquireInfo(String msg) {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    /**
     * 选择出生年月
     */
    public void onChooseYearAndMonth() {
        Calendar calendar = Calendar.getInstance();
        DatePicker picker = new DatePicker(this);
        picker.setRange(2000, 2030);
        picker.setSelectedItem(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
//                toast(year + "-" + month + "-" + day);

                str_age = year + "-" + month + "-" + day;
                tvAge.setText(str_age);

                Map map = new HashMap();
                map.put("id", new UserUtil(OwnInfoActivity.this).getUserId());
                map.put("sex", year + "-" + month + "-" + day);
                String json = StringUtil.toJson(map);
                try {
                    String data1 = AESCrypt.getInstance().encrypt(json);
                    String d = StringUtil.replaceBlank(data1);
                    presenter.ChangeInfo(d);
                } catch (Exception ex) {
                }
            }
        });
        picker.show();
    }

    /**
     * 选择性别
     */
    public void onChooseSex() {
        SexPicker picker = new SexPicker(this);
        //picker.onlyMaleAndFemale();
        picker.setOnOptionPickListener(new OptionPicker.OnOptionPickListener() {
            @Override
            public void onOptionPicked(String option) {
//                toast(option);
                str_sex = option;
                tvSex.setText(str_sex);

                Map map = new HashMap();
                map.put("id", new UserUtil(OwnInfoActivity.this).getUserId());
                map.put("sex", option);
                String json = StringUtil.toJson(map);
                try {
                    String data1 = AESCrypt.getInstance().encrypt(json);
                    String d = StringUtil.replaceBlank(data1);
                    presenter.ChangeInfo(d);
                } catch (Exception ex) {
                }
            }
        });
        picker.show();
    }
}
